package com.example.redission.controller;

import com.example.redission.client.CustomRedissonClient;
import com.example.redission.client.CustomRedissonRateLimiter;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*
 * 限流器
 * 1.先调用init方法生成5个令牌
 * 2.通过该限流器的名称rateLimiter来获取令牌limiter.tryAcquire()
 * 3.谁抢到,谁先执行,否则返回提示信息,可以用于秒杀场景
 * */
@RestController
@RequestMapping("/limiter")
public class RateLimiterController {
    @Autowired
    private RedissonClient redissonClient;

    private RedissonClient customRedisson;

    //初始化限流器
    @RequestMapping("/init")
    public void init() {
        customRedisson = CustomRedissonClient.create(redissonClient.getConfig());
        RRateLimiter rateLimiter = customRedisson.getRateLimiter("rateLimiter");
        rateLimiter.trySetRate(RateType.OVERALL, 6, 1, RateIntervalUnit.MINUTES);//每1秒产生5个令牌

//        RRateLimiter limiter = redissonClient.getRateLimiter("rateLimiter");
//        limiter.trySetRate(RateType.OVERALL, 6, 1, RateIntervalUnit.MINUTES);//每1秒产生5个令牌
    }

    //获取令牌
    @GetMapping("/thread")
    public void thread(Integer value) {
        RRateLimiter limiter = customRedisson.getRateLimiter("rateLimiter");
        CustomRedissonRateLimiter cus = (CustomRedissonRateLimiter)limiter;
        if (cus.tryAcquire(value)) {//尝试获取1个令牌
            System.out.println(Thread.currentThread().getName() + "成功获取到令牌");
        } else {
            System.out.println(Thread.currentThread().getName() + "未获取到令牌");
        }
    }

    //获取令牌
    @RequestMapping("/thread2")
    public void thread2(Integer value) {
        RRateLimiter limiter = redissonClient.getRateLimiter("rateLimiter");
        long l = limiter.availablePermits();
        if (limiter.tryAcquire(value)) {//尝试获取1个令牌
            System.out.println(Thread.currentThread().getName() + "成功获取到令牌");
        } else {
            System.out.println(Thread.currentThread().getName() + "未获取到令牌");
        }
    }
}
